from flask import current_app, session, request, jsonify, g
from flask_sqlalchemy import Pagination
from sqlalchemy.sql.functions import user

from info import sr, db
from info.constants import CLICK_RANK_MAX_NEWS, HOME_PAGE_MAX_NEWS
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.response_code import error_map, RET
from . import home_blu
import logging  # 系统内置的日志模块  可以将日志信息打印在控制台, 也可以保存到文件中
from flask import render_template


# 2.使用蓝图装饰路由
@home_blu.route('/')
@user_login_data
def index():

    # 从数据库中取出点击量最多的6条新闻, 进行模板渲染
    rank_list = []  # type: list[News]
    try:
        rank_list = News.query.order_by(News.clicks.desc()).limit(CLICK_RANK_MAX_NEWS).all()
    except BaseException as e:
        current_app.logger.error(e)

    # 从数据库中取出分类信息, 然后模板渲染
    try:
        categories = Category.query.all()  # type: list[Category]
    except BaseException as e:
        current_app.logger.error(e)

    user = g.user.to_dict() if g.user else None
    # 如果登录, 将用户信息传到模板中, 进行模板渲染
    return render_template("news/index.html", user=user, rank_list=rank_list, categories=categories)


# 设置网站小图标
@home_blu.route('/favicon.ico')
def get_favicon():
    # 返回静态文件
    return current_app.send_static_file("news/favicon.ico")


# 获取新闻列表
@home_blu.route('/get_news_list')
def get_news_list():
    # 获取参数
    cid = request.args.get("cid")
    cur_page = request.args.get("cur_page")
    per_count = request.args.get("per_count", HOME_PAGE_MAX_NEWS)
    # 校验参数
    if not all([cid, cur_page]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 格式转换
    try:
        cid = int(cid)
        cur_page = int(cur_page)
        per_count = int(per_count)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    filter_list = [News.status == 0]
    if cid != 1:
        filter_list.append(News.category_id == cid)

    # 根据参数从数据库中取出新闻列表  根据分类, 发布时间倒序, 分页取出数据
    try:
        pn = News.query.filter(*filter_list).order_by(News.create_time.desc()).paginate(cur_page, per_count)  # type: Pagination
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    # 封装成json返回
    data = {
        "news_list": [news.to_dict() for news in pn.items],  # 新闻列表数据 包含都是字典形式的新闻数据
        "total_page": pn.pages  # 总页数
    }
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], data=data)